var consts = require('../../../util/consts');
var logger = require('pomelo-logger').getLogger('user-handler', 'userHandler');
var utils = require('../../../util/utils');
var lottery = require('../../../util/lottery');
var async = require('async');

module.exports = function (app) {
    return new Handler(app);
}

var Handler = function (app) {
    this.app = app;
    this.consts = consts;
};

var handler = Handler.prototype;

/**
 * 转盘抽奖
 * @param msg
 * @param session
 * @param next
 */
handler.c2sDrawLottery = function (msg, session, next) {
    var self = this;
    var uid = session.get('uid');

    self.app.rpc.login.loginRemote.getUser(session, uid, function (err, userInfo) {
        if (!userInfo) {
            next(null, {
                code: self.consts.Code.ERR,
                msg: self.consts.Msg.USER_NOT_FOUND
            });
            return;
        }
        //抽奖次数不足
        if (userInfo.luck_draw_num < 1) {
            next(null, {
                code: self.consts.Code.ERR,
                msg: self.consts.Msg.LOTTERY_INSUFFICIENT_ERR
            });
            return;
        }
        var draw = new lottery.Draw(lottery.reward);
        //随机获取转盘奖励
        let result = draw.getResult();
        //领取转盘奖励
        self.app.rpc.login.loginRemote.receiveLottery(session, uid, session.frontendId, result, function () {
        });
        let totalPro = utils.calTotalProduction(userInfo.levelInfo);
        if (result.value == 'no1') {
            totalPro = totalPro * 3000;
        } else if (result.value == 'no2') {
            totalPro = totalPro * 5000;
        } else if (result.value == 'no3') {
            totalPro = totalPro * 2000;
        } else if (result.value == 'no5') {
            totalPro = totalPro * 1500;
        } else if (result.value == 'no4') {
            result.coins = 3;
        } else {
            result.coins = 2;
        }

        async.waterfall([
            function (callback) {
                if (result.value != 'no4' && result.value != 'no6') {
                    //徒弟助力金币加成
                    utils.apprenticeHelpNum(userInfo.uid, function (err, num) {
                        //无异常、且助力加成大于0
                        if (!err && num > 0) {
                            let help = parseFloat((num / 100).toFixed(2));
                            result.coins = utils.formatCoins(totalPro + totalPro * help);
                        } else {
                            //格式化金币输出
                            result.coins = utils.formatCoins(totalPro);
                        }
                        callback(null, result);
                    });
                } else {
                    callback(null, result);
                }
            }
        ], function (err, result) {
            next(null, {
                code: self.consts.Code.SUC,
                msg: self.consts.Msg.RESULT_SUCCESS,
                data: result
            });
            return;
        });
    });
}



